//
//  JMLeftViewController.m
//  分页控制器
//
//  Created by JackMeng on 16/3/18.
//  Copyright © 2016年 JackMeng. All rights reserved.
//

#import "JMLeftViewController.h"
#import "ProvinceDetailController.h"


@interface JMLeftViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tableVIew;

@property (nonatomic,strong) UIView *View1;

//记录点击的btn

@property (nonatomic,strong) UIButton *lastBtn;

@property (nonatomic,assign) NSInteger currentPage;


@end

@implementation JMLeftViewController

static NSString *const ID = @"Cell";

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
     UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"]  style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
//rightButton.frame = CGRectMake(0, 0, 44, 44);
//[rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];

//[rightButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateDisabled];
// 

    [self.navigationItem setRightBarButtonItem:rightButton];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *view1 = [[UIView alloc] init];
        
    self.View1 = view1;
    
    [self.view addSubview:view1];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top);
        
        make.left.equalTo(self.view.mas_left);
        
        make.right.equalTo(self.view.mas_right);
        
        make.height.equalTo(@110);
    }];

    
    UITableView *tab = [[UITableView alloc] init];
    
    self.tableVIew = tab;
    
    tab.delegate = self;
    
    tab.dataSource = self;
    
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view1.mas_bottom);
        
        make.left.equalTo(self.view.mas_left);
        
        make.right.equalTo(self.view.mas_right);
        
        make.bottom.equalTo(self.view.mas_bottom);
    }];

    [self setUp];
    
    __weak typeof (self) weakSelf = self;
    
    [self.tableVIew addHeaderWithCallback:^{
        
        [weakSelf loadData]; //加载网络数据
        
        
    }];
    [self.tableVIew headerBeginRefreshing];
    
    [self.tableVIew addFooterWithCallback:^{
        
        [weakSelf loadMore];
        
    }];
}

- (void)loadData{

    //省本级会员
    
    self.currentPage = 1;
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getSLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%ld,branch:0}'}",userId,pwdId,userHumber,self.currentPage];
    
    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
                
            [self.dataArray addObject:leftM];
            
        }
        
        [self.tableVIew headerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];


}

- (void)loadMore{

    self.currentPage ++;
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getJCLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%ld }'}",userId,pwdId,userHumber,self.currentPage];
    
    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
            
            [self.dataArray addObject:leftM];
            
        }
        
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"没有最新数据哦"];
        }
        [self.tableVIew footerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];

}


- (void)setUp{
    
    CGFloat W = (self.view.width - 50) / 4;
    
    CGFloat H = 30;
    
    NSArray *arr = @[@"全部单位",@"副会长单位",@"常务理事单位",@"理事单位",@"普通会员",@"潜在会员"];
    
    for (int i = 0 ; i < arr.count; i ++) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.layer.cornerRadius = 15;
        [btn.layer setBorderColor:[UIColor orangeColor].CGColor];
        [btn.layer setBorderWidth:1];
        btn.layer.masksToBounds = YES;
        
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        
        if ([btn.titleLabel.text isEqualToString:@"全部单位"]) {
            
            btn.tag = 0;
        }else if ([btn.titleLabel.text isEqualToString:@"副会长单位"]){
            btn.tag = 4;
            
        }else if ([btn.titleLabel.text isEqualToString:@"常务理事单位"]){
            btn.tag = 3;

        }else if ([btn.titleLabel.text isEqualToString:@"理事单位"]){
            btn.tag = 2;

        }else if ([btn.titleLabel.text isEqualToString:@"普通会员"]){
            btn.tag = 1;

        }else if ([btn.titleLabel.text isEqualToString:@"潜在会员"]){
            btn.tag = 5;

        }
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:11];
        
        btn.backgroundColor = [UIColor whiteColor];
        
        CGFloat WH = 10 *(i + 1) + W*i;
        CGFloat Y = 15;
        if (WH > 40 + 3*W) {
            
            WH = 10 *(i - 3) +W*(i - 4);
            Y += 40;
        }
        
        btn.frame = CGRectMake(WH, Y, W, H);
        
        [self.View1 addSubview:btn];
        
    }

}

- (void)btnClick:(UIButton *)btn{

    self.lastBtn.backgroundColor = [UIColor whiteColor];
    
    [self.lastBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
    btn.backgroundColor = [UIColor orangeColor];

    [self.dataArray removeAllObjects];
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getSLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%d, branch:%ld}'}",userId,pwdId,userHumber,1,btn.tag];

    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
            
            [self.dataArray addObject:leftM];
            
        }
        
        self.lastBtn = btn;
        
        [self.tableVIew headerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return  self.dataArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    leftModel *model = self.dataArray[indexPath.row];
    
    leftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        
    cell = [leftTableViewCell WithLeftTableViewCell];
        
    }
    
    cell.model = model;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 60;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    leftModel *model = self.dataArray[indexPath.row];

    ProvinceDetailController *proVC = [[ProvinceDetailController alloc] init];

    proVC.contId = model.ID;
    
    [self.navigationController pushViewController:proVC animated:YES];
    
}



@end














